import 'dart:io';

import 'package:logger/logger.dart';
import 'package:path_provider/path_provider.dart';

class Log {
  _() {}
  static Logger? _logger;

  static Future<void> init() async {
    final fileOutput = await _FileLogOutput.create();
    _logger = Logger(
      printer: PrettyPrinter(
        methodCount: 0,
        errorMethodCount: 0,
        lineLength: 120,
        colors: true,
        printEmojis: true,
        dateTimeFormat: DateTimeFormat.dateAndTime,
      ),
      output: MultiOutput([
        ConsoleOutput(),
        fileOutput, // 👈 已经初始化好的
      ]),
    );
  }
  static i(dynamic msg) {
    _logger?.log(Level.info, msg);
  }

  static e(dynamic msg) {
    _logger?.log(Level.error, msg);
  }

  static w(dynamic msg) {
    _logger?.log(Level.warning, msg);
  }

  static d(dynamic msg) {
    _logger?.log(Level.debug, msg);
  }
}

class _FileLogOutput extends LogOutput {
  late File logFile;

  _FileLogOutput._(this.logFile);

  static Future<_FileLogOutput> create() async {
    final dir = await getApplicationCacheDirectory();
    final logDir = Directory('${dir.path}/log');
    if (!await logDir.exists()) {
      await logDir.create(recursive: true); // 递归创建，确保路径存在
    }
    final date = DateTime.now();
    final fileName = '${date.year}-${date.month}-${date.day}.log';
    final file = File('${logDir.path}/$fileName');
    if (!await file.exists()) {
      await file.create();
    }
    return _FileLogOutput._(file);
  }

  @override
  void output(OutputEvent event) {
    final log = '${event.origin.time} [${event.level.name}] ${event.origin.message}';
    logFile.writeAsStringSync('$log\n', mode: FileMode.append, flush: true);
  }
}
